<?php

namespace app\data\controller\report;

use app\data\command\ReportDailyOutput;
use app\data\command\ReportObservation;
use app\data\service\DailyOutputService;
use think\admin\Controller;

/**
 * 数据统计-城市人力施工分析表
 * Class StatisticsDailyPower
 * @package app\data\controller\report
 */
class StatisticsDailyPower extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'report_daily_output';

    /**
     * 城市人力施工分析表
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        // 设置页面标题
        $this->title = '城市人力施工分析表';

        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $date = $this->request->request('date');
        if (empty($date)) {
            $date = $this->yesterday = $yesterday . ' - ' . $yesterday;
        } else {
            $this->yesterday = $yesterday;
        }

        [$minDate, $maxDate] = explode(' - ', $date);

        if ($minDate == $maxDate) {
            $this->isSingleDay = true;
            if ($minDate == date('Y-m-d')) {
                $this->error('今日数据尚未生成，请明天重试');
            }

            $this->app->db->name('report_daily_output')->where('date', $minDate)->delete();
            DailyOutputService::instance()->formatDate($minDate, ($minDate . ' 23:59:59'));

            $this->show_date = date('m/d', strtotime($minDate));
            $result = $this->_query($this->table)->where('date', $minDate)->order('from_province desc, from_city desc');
        } else {
            $this->isSingleDay = false;
            $this->app->db->name('report_daily_output')
                ->where('date', '>=', $minDate)
                ->where('date', '<=', $maxDate)
                ->delete();
            DailyOutputService::instance()->formatDate($minDate, ($maxDate . ' 23:59:59'));

            $query = $this->_query($this->table)->whereBetweenTime('date', $minDate, $maxDate);

            $this->show_date = date('m/d', strtotime($minDate)) . '-' . date('m/d', strtotime($maxDate));

            $result = $query->group('from_city')->field('from_city, from_province, SUM(real_group_power) AS real_group_power, SUM(energy) AS energy, SUM(group_energy) AS group_energy, SUM(people_power) AS people_power, SUM(complete_count) AS complete_count, SUM(complete_today_count) AS complete_today_count, SUM(diff) AS diff, SUM(count_diff) AS count_diff, SUM(real_diff) AS real_diff, MAX(not_complete_count) AS not_complete_count,SUM(not_complete_today_count) AS not_complete_today_count,MAX(all_record_count) AS all_record_count,MAX(all_complete_count) AS all_complete_count, SUM(record_count) AS record_count, GROUP_CONCAT(cancel_order_json SEPARATOR "###") AS cancel_order_json')->order('date desc');
        }

        // 数据查询分页
        if (input('output') == 'json') {
            $result = $result->page(true, false, false, 10000);
            $this->success('', $result);
        } else {
            $result->page(false, true, false, 10000);
        }
    }

    /**
     * 未做订单导出
     * @auth true
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function export()
    {
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $date = $this->request->request('date', $yesterday);
        if (empty($date)) {
            $date = $this->yesterday = $yesterday . ' - ' . $yesterday;
        } else {
            $this->yesterday = $yesterday;
        }

        [$minDate, $maxDate] = explode(' - ', $date);
        if ($minDate == $maxDate) {
            if ($date == date('Y-m-d')) {
                $this->error('今日数据尚未生成，请明天重试');
            }
        }

        $this->yesterday = $yesterday;
        $result = $this->app->db->name($this->table)->whereBetween('date', [$minDate, $maxDate])->order('from_province desc, from_city desc')->select()->toArray();
        $result = array_column($result, 'cancel_order_json');

        $list = [];
        foreach ($result as $item) {
            $item = json_decode($item, true);
            $list = array_merge($list, array_column($item, 'remark'));
        }

        $this->success('', [
            'page' => ['limit' => count($list), 'total' => count($list), 'page' => 1, 'current' => 1],
            'list' => $list
        ]);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$item) {
            $item['cancel_order_json'] = explode('###', $item['cancel_order_json']);
            $item['format_remark'] = [];
            foreach ($item['cancel_order_json'] as $formatMark) {
                $remark = json_decode($formatMark, true);
                if (!empty($remark)) {
                    if (empty($item['format_remark'])) {
                        $item['format_remark'] = $remark;
                    } else {
                        $item['format_remark'] = array_merge($item['format_remark'], $remark);
                    }

                    if (empty($recordIds)) {
                        $recordIds = array_column($remark, 'id');
                    } else {
                        $recordIds = array_merge($recordIds, array_column($remark, 'id'));
                    }
                }
            }

            // 总完工率=已完工数/派单总数*100%；
            // 完工率=止筛选时间完工数/筛选时间派单数*100%(当前时间-1的时间，tal为时间，在时间内施工完成的数量);
        }

        if (!empty($recordIds)) {
            $completeIds = $this->app->db->name('data_record')->whereIn('id', $recordIds)->where('paint_status', 1)->column('id');
        }

        foreach ($data as &$item) {
            foreach ($item['format_remark'] as $key => $formatRemark) {
                $item['format_remark'][$key]['remark'] = ($key + 1) . '.'. $formatRemark['remark'];
                $item['format_remark'][$key]['is_complete'] = in_array($formatRemark['id'], $completeIds ?? []) ? 1 : 0;
            }

            if ($item['all_record_count'] == 0) {
                $item['all_complete_count_rate'] = 0;
            } else {
                $item['all_complete_count_rate'] = bcmul(bcdiv($item['all_complete_count'], $item['all_record_count'], 4), 100, 2);
            }

            if ($item['record_count'] == 0) {
                $item['today_complete_count_rate'] = 0;
            } else {
                $item['today_complete_count_rate'] = bcmul(bcdiv($item['complete_today_count'], $item['record_count'], 4), 100, 2);
            }
        }

        // 单元格合并
//        $fromProvince = array_column($data, 'from_province');
//        $counts = array_count_values($fromProvince);
//        $existProvince = [];
//        foreach ($data as $key => &$item) {
//            if (!in_array($item['from_province'], $existProvince)) {
//                $item['rowspan'] = $counts[$item['from_province']] ?? 0;
//                $existProvince[] = $item['from_province'];
//
//                $item['province_complete_count_count'] = $this->fromatNumber($data, 'complete_count', $key, $item['rowspan']);
//                $item['province_record_count'] = $this->fromatNumber($data, 'record_count', $key, $item['rowspan']);
//                $item['province_group_energy'] = $this->fromatNumber($data, 'group_energy', $key, $item['rowspan']);
//                $item['province_real_diff'] = $this->fromatNumber($data, 'real_diff', $key, $item['rowspan']);
//                $item['format_remark'] = implode(PHP_EOL, $this->fromatNumber($data, 'format_remark', $key, $item['rowspan']));
//            }
//        }

        // 合计
        foreach($data as $sumItem) {
            foreach ($sumItem as $key => $value) {
                $str = 'sum_' . $key;
                if (!in_array($key, [
                    'id',
                    'date',
                    'city_relation_id',
                    'from_city',
                    'from_province',
                    'cancel_order_json',
                    'format_remark',
                    'rowspan',
                ])) {
                    if (!isset($this->sumList[$str])) {
                        $this->sumList[$str] = $value;
                    } else {
                        $this->sumList[$str] = $this->sumList[$str] + $value;
                    }
                }
            }
        }

        if (!empty($this->sumList)) {
            if (empty($this->sumList['sum_all_record_count'])) {
                $this->sumList['sum_all_complete_count_rate'] = 0;
            } else {
                $this->sumList['sum_all_complete_count_rate'] = bcmul(bcdiv($this->sumList['sum_not_complete_count'], $this->sumList['sum_all_record_count'], 4), 100, 2);
            }

            if (empty($this->sumList['sum_record_count'])) {
                $this->sumList['sum_today_complete_count_rate'] = 0;
            } else {
                $this->sumList['sum_today_complete_count_rate'] = bcmul(bcdiv($this->sumList['sum_complete_today_count'], $this->sumList['sum_record_count'], 4), 100, 2);
            }
        }

    }

    private function fromatNumber($data, $field, $start, $count)
    {
        if ($field == 'format_remark') {
            $response = [];
        } else {
            $response = 0;
        }

        for ($i = 0; $i <= ($count - 1); $i++) {
            $n = $start + $i;
            if ($field == 'format_remark') {
                $response = array_merge($response, explode(PHP_EOL, $data[$n][$field]));
            } else {
                $response = $response + $data[$n][$field];
            }
        }

        if ($field == 'format_remark') {
            $n = 0;
            foreach($response as $key => $item) {
                if (!empty($item)) {
                    $n++;
                    $response[$key] = $n . '.' . $item;
                }
            }
        }

        return $response;
    }

    /**
     * 更新
     * @menu true
     */
    public function retrySync()
    {
        $data = $this->_vali([
            'date.require' => '时间不能为空！',
        ]);
        [$minDate, $maxDate] = explode(' - ', $data['date']);
        if ($minDate != $maxDate) {
            $this->error('时间范围请选择一天内');
        }

        $this->app->db->name('report_daily_output')->where('date', $minDate)->delete();

        DailyOutputService::instance()->formatDate($minDate, ($maxDate . ' 23:59:59'));

        $this->success('更新成功');
    }
}